File Handling in Python

TERMS

  • A file is a collection of data stored on a secondary storage device like hard disk.

  • Absolute Path contains root while Relative path needs to be combined with another path to access a file

  • A text file is a stream of characters that can be sequentially processed by a computer in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.

  • A binary file is a file which may contain any type of data, encoded in binary form for computer storage and processing purposes.

OPEN() FUNCTION

Syntax

fileObj = open(file_name [, access_mode]) 

file = open(file.txt,'rb')
print(file)

File Access Modes

image.png

Magic Command

%%writefile hello.txt
this is a python text file.
Overwriting hello.txt

OPEN FILE

t = open('hello.txt','r')

ACCESS FILE

for i in t:
    print(i)
this is a python text file.

WRITE FILE

t = open('hello.txt','w')
t.write("this is great")
t.close()
t = open('hello.txt','w')
for i in t:
    print(i)
UnsupportedOperation: not readable
t.close()

File object Attributes

print(t.mode)
print(t.name)
print(t.closed)
w
hello.txt
True

FILE RENAME

import os 
os.rename('hello.txt','hello1.txt')

WRITE AND WRITELINES

  • The write() method writes any string to an open file.
  • The write() method does not add a newline character ('\n') to the end of the string.
  • The writelines() method takes a list and write each entry in its own line (if it has the “” character at the end).

WRITELINES()

  • The writelines() method is used to write a list of strings.

file = open("hello1.txt", "w") 
lines = ["Hello World,\n", "Welcome to the world of Python\n", "Enjoy Learning Python"] 
file.writelines(lines)

file. close() 
file = open("hello1.txt", "r") 
for i in file:
    print(i)
Hello World,

Welcome to the world of Python

Enjoy Learning Python

print("Data written to file...")
Data written to file...

PRESENT WORKING DIRECTORY

pwd
'C:\\Users\\Lenovo\\PYTHON'

VARIABLE INSPECTOR

whos
Variable   Type             Data/Info
-------------------------------------
file       TextIOWrapper    <_io.TextIOWrapper name='<...>de='w' encoding='cp1252'>
i          str               Python is a very simple yet powerful language
line       str              this is a python text file.\n
lines      list             n=3
os         module           <module 'os' (frozen)>
t          TextIOWrapper    <_io.TextIOWrapper name='<...>de='r' encoding='cp1252'>
words      list             n=6

Append Method

  • To append a file, you must open it using ‘a’ or ‘ab’ mode depending on whether it is a text file or a binary file.
  • Note that if you open a file in ‘w’ or ‘wb’ mode and then start writing data into it, then its existing contents would be overwritten.

EXAMPLE

file = open("hello1.txt", "a" )
file.write("\n Python is a very simple yet powerful language") 
file.close() 
print("Data appended to file.. . . ") 
Data appended to file.. . . 
file.close() 

DISPLAY FILE CONTENT

t = open('hello1.txt','r')
for i in t:
    print(i)
Hello World, Welcome to the world of Python Enjoy Learning Python

 Python is a very simple yet powerful language

The read() and readline() Methods

fileObj.read([count])
- The read() method starts reading from the beginning of the file and if count is missing or has a negative value then, it reads the entire contents of the file (i.e., till the end of file). - The readlines() method is used to read all the lines in the file

EXAMPLE

file = open( 'hello1.txt', 'r')
print(file.read(10))
file.close()
Hello Worl

WITH KEYWORD

Using without WITH KEYWORD

file = open( 'hello1.txt', 'r')
for line in file: 
    print(line) 
print("is the file closed? ", file.closed)
Hello World, Welcome to the world of Python Enjoy Learning Python

 Python is a very simple yet powerful language
is the file closed?  False

Using WITH KEYWORD

with open( 'hello1.txt', 'r') as file: 
    for line in file: 
        print(line) 
print("is the file closed? ", file.closed)
Hello World, Welcome to the world of Python Enjoy Learning Python

 Python is a very simple yet powerful language
is the file closed?  True

SPLIT WORDS

EXAMPLE

with open( 'hello1.txt', 'r') as file: 
    line = file. readline() 
    words = line.split() 
    print(words) 
['Hello', 'World,', 'Welcome', 'to', 'the', 'world', 'of', 'Python', 'Enjoy', 'Learning', 'Python']
t = open('hello1.txt','r')
t.fileno()
3

FILE POSITION

  • With every file, the file management system associates a pointer often known as file pointer that facilitate the movement across the file for reading and/ or writing data.

  • Python has various methods that tells or sets the position of the file pointer.

  • For example, the tell() method tells the current position within the file at which the next read or write operation will occur. It is specified as number of bytes from the beginning of the file.

  • The seek(offset[, from]) method is used to set the position of the file pointer or in simpler terms, move the file pointer to a new location. The offset argument indicates the number of bytes to be moved and the from argument specifies the reference position from where the bytes are to be moved.

EXAMPLE

file = open("hello1.txt","rb") 
print("Position of file pointer before reading is - ", file.tell()) 
print (file.read(10)) 
print("Position of file pointer after reading is - ", file.tell()) 
print("Setting 3 bytes from the current position of file pointer")
file.seek(3, 1) 
print(file.read()) 
file.close() 
Position of file pointer before reading is -  0
b'Hello Worl'
Position of file pointer after reading is -  10
Setting 3 bytes from the current position of file pointer
b'Welcome to the world of Python Enjoy Learning Python\r\n Python is a very simple yet powerful language'

Summary of basic file IO functions and methods

Methods and functions Description
open() Returns a file object and is most commonly used with two arguments: open(filename, mode)
file.close() Close the file.
file.read([size]) Read the entire file. If size is specified then read at most size bytes.
file.readline([size]) Read one line from the file. If size is specified then read at most size bytes.
file.readlines([size]) Read all the lines from the file. If size is specified then read at most size bytes.
file.tell() Returns file object’s current position in the file.
file.seek(int) Changes the file object’s current position to the given int.
file.write(string) Writes the contents of string to the file.
file.writelines(string) Writes the list of contents of string to the file.